package 重温_Java并发基础.CompletableFuture案例.串行执行;


import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
 * @author idea
 * @data 2020/2/22
 */



public class SeqDemo {

    static class StockName implements Supplier<String> {

        private String name;

        public StockName(String name) {
            this.name = name;
        }

        @Override
        public String get() {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return name;
        }
    }

    static class StockPriceItem implements Supplier<Integer> {
        private Integer price;

        private String name;

        public StockPriceItem(Integer price, String name) {
            this.price = price;
            this.name = name;
        }

        @Override
        public java.lang.String toString() {
            return price+":"+name;
        }

        @Override
        public Integer get() {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return price;
        }
    }

    public void query(){
        CompletableFuture<String> getNameFuture=CompletableFuture.supplyAsync(new StockName("idea"));
        CompletableFuture<StockPriceItem> getStorckPriceItem=getNameFuture.thenApplyAsync(new Function<String, StockPriceItem>() {
            @Override
            public StockPriceItem apply(String name) {
                return new StockPriceItem(-1,name);
            }
        });
        getStorckPriceItem.thenAccept(new Consumer<StockPriceItem>() {
            @Override
            public void accept(StockPriceItem stockPriceItem) {
                System.out.println(stockPriceItem.toString());
            }
        });
        getStorckPriceItem.join();
    }

    public static void main(String[] args) {
        SeqDemo seqDemo=new SeqDemo();
        seqDemo.query();
    }
}
